<template>
  <div>
    <attach-detail :project-data="projectData"></attach-detail>
    <h3 class="attach-title">附件资料</h3>
    <hr />
    <attach-list v-loading="loading" :attath-data="uploadList" :show-label="showLabel">
      <div slot="corp">
        <c-radio-group
          :disabled="viewMode"
          @change="updateCorp(1)"
          :options="[
            { label: '是', value: '1' },
            { label: '否', value: '0' },
          ]"
          v-model="isCorp"
        ></c-radio-group>
      </div>
      <template slot="tagAction" slot-scope="{ tagData }" v-if="!viewMode">
        <el-button
          type="primary"
          size="small"
          class="btn-long mb-1"
          icon="el-icon-upload2"
          @click="handleUpload(tagData.tag)"
        >
          上传
        </el-button>
      </template>
      <template slot="attachAction" slot-scope="{ attachData }">
        <el-button type="text" @click="handleDeleteFile(attachData)">
          <span class="text-danger">删除</span>
        </el-button>
      </template>

      <template slot="contract">
        <attach-contract
          :related-id="queryId"
          :view-mode="viewMode"
          :tag="contractTag"
          @get-contract="handleGetContract"
          @type-change="handleContractTypeChange"
          @success="handleContractSuccess"
        ></attach-contract>
      </template>
    </attach-list>

    <attach-upload-dialog
      :visible.sync="uploadVisible"
      :attach-tag="uploadAttachTag"
      :attach-id="queryId"
      v-bind="$attrs"
      @success="onUploadSuccess"
    ></attach-upload-dialog>
  </div>
</template>

<script>
import { projectIsCompany } from '@/bank/views/limit/index'

import AttachDetail from '@/bank/views/business/limit/history/attach/AttachDetail'
import AttachList from '@/bank/views/business/limit/history/attach/AttachList'
import AttachUploadDialog from '@/bank/components/attach/UploadDialog'
import { attachAdapter } from '@/bank/components/attach/index'
import AttachContract from '@/bank/views/business/limit/new/attach/AttachContract'
import { deleteOss } from '@/common/api/oss'

export const enumPersonBaseTags = [
  { tag: '委保合同', required: true, slot: 'contract' },
  { tag: '资信表或尽调报告', required: true },
  { tag: '委托担保函', required: true },
  { tag: '委托担保项目表', required: true },
  { tag: '借据', required: false },
  { tag: '借款合同', required: false },
  { tag: '身份证或户口本', required: false },
  { tag: '结婚证', required: false },
  { tag: '其他', required: false },
]
export const enumCompanyBaseTags = [
  { tag: '委保合同', required: true, slot: 'contract' },
  { tag: '资信表或尽调报告', required: true },
  { tag: '个人责任承诺函', required: true },
  { tag: '委托担保函', required: true },
  { tag: '委托担保项目表', required: true },
  { tag: '借据', required: false },
  { tag: '借款合同', required: false },
  { tag: '营业执照', required: false },
  { tag: '法定代表人身份证或户口本', required: false },
  { tag: '实际控制人是否是法人', slot: 'corp' },
  { tag: '实际控制人身份证或户口本', required: false },
  { tag: '其他', required: false },
]

export const enumRenewalTags = [
  { tag: '委保合同', required: true, slot: 'contract' },
  { tag: '借款合同或借据', required: false },
]
export default {
  components: {
    AttachDetail,
    AttachList,
    AttachUploadDialog,
    AttachContract,
  },
  props: {
    queryId: String,
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      showLabel: true,
      uploadVisible: false,
      uploadAttachTag: '',
      tableName: 'datum_customer_attachment',
      uploadList: [],
      isCorp: '1',
      projectData: {},
      isOnlineSign: 2,
      signStatus: 0,
      currentStatus: 0,
      customerSignApproval: 0,
      attachs: [],
    }
  },
  computed: {
    enumRenewalTagsShow() {
      return this.viewMode
        ? [...enumRenewalTags, { tag: '其他', required: false }]
        : enumRenewalTags
    },
    isCompany() {
      // return true
      return projectIsCompany(this.projectData)
    },
    // 是否续贷
    isContinue() {
      return +(this.projectData.renewal_type || '') === 2
    },
    uploadTags() {
      return this.isContinue
        ? this.enumRenewalTagsShow
        : this.isCompany
        ? enumCompanyBaseTags
        : enumPersonBaseTags
    },
    contractTag() {
      const tag = this.uploadTags.find(it => it.slot === 'contract') || {}
      return {
        tag: tag.tag,
        required: tag.required,
      }
    },
  },
  watch: {
    queryId: {
      handler: async function () {
        await this.getItemData()
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getItemData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      return this.$api
        .getData(this.$serviceName, 'datum_one_county_industry', {
          'customer_related_id.eq': this.queryId,
        })
        .then(res => {
          const data = res?.data?.[0] ?? {}
          this.projectData = data
          this.isCorp = data.is_corp_con || '1'
        })
        .finally(() => {
          this.loading = false
        })
    },
    reset() {
      if (+this.isCorp === 1) {
        this.uploadList = this.uploadTags
          .filter(item => item.tag !== '实际控制人身份证或户口本')
          .map(item => ({
            ...item,
            attachs: [],
          }))
      } else {
        this.uploadList = this.uploadTags.map(item => ({
          ...item,
          attachs: [],
        }))
      }
    },
    handleUpload(tag) {
      this.uploadAttachTag = tag
      this.uploadVisible = true
    },
    onUploadSuccess() {
      this.getData(1)
    },
    handleContractSuccess() {
      this.signStatus = 1
      this.updateStatus()
    },

    // 委托合同附件
    handleGetContract({ contract }) {
      this.isOnlineSign = +(contract.is_online_sign || 0)
      this.signStatus = +(contract.sign_status || 0)
      this.customerSignApproval = +(contract.customer_sign_approval || 0)
    },

    handleContractTypeChange(type) {
      this.isOnlineSign = type
      this.$emit('after-data', {})
      this.updateStatus()
    },
    getData(status = 0) {
      if (!this.queryId) {
        return
      }

      this.loading = true
      this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          { 'customer_related_id.eq': this.queryId },
          { create_time: 'desc' }
        )
        .then(res => {
          const data = res?.data ?? []
          this.attachs = data
          this.reset()

          for (const attach of data) {
            const attachData = attachAdapter(attach)

            let index = this.uploadList.findIndex(it => it.tag === attach.attachment_type)

            // 追加未归类的标签到固定分类中。最后一个已经初始化为otherTag（客户基础资料）了
            if (index < 0) {
              index = this.uploadList.length - 1
            }
            this.uploadList[index].attachs.push(attachData)
          }
          if (status === 1) {
            this.updateStatus()
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    updateCorp() {
      this.$api
        .updateData({
          table: 'datum_one_county_industry',
          id: this.queryId,
          data: {
            is_corp_con: this.isCorp,
          },
        })
        .then(() => {
          this.updateStatus()
        })
    },
    // 更新项目附件状态
    updateStatus() {
      // 判断附件状态
      const listObj = this.attachs.reduce((prev, curr) => {
        const tag = curr.attachment_type
        if (!prev[tag]) prev[tag] = []
        prev[tag].push(curr)
        return prev
      }, {})
      const isAllUpload = this.uploadTags.every(tag => {
        const isOnline = tag.slot === 'contract' && this.isOnlineSign === 1
        if (isOnline) {
          return this.customerSignApproval === 1
        }
        if (!tag.required) return true
        const atts = listObj[tag.tag]
        return atts && atts.length > 0
      })
      const currentStatus = isAllUpload ? 1 : 0
      const attachStatus = +this.projectData.datum_status
      if (attachStatus === currentStatus) {
        return this.$emit('after-data', {})
      }

      // 更新状态
      this.$api
        .updateData({
          table: 'datum_one_county_industry',
          id: this.queryId,
          data: {
            datum_status: currentStatus,
            is_corp_con: this.isCorp,
          },
        })
        .then(() => {
          // 观察：更改 props 对象值
          this.projectData.datum_status = currentStatus
        })
        .finally(() => {
          this.$emit('success', {})
        })
    },
    handleDeleteFile(attach) {
      const { attachment: url, id } = attach
      this.$utils
        .msgbox({
          message: '确定删除此附件?',
          beforeClose: () => this.deleteData(id),
        })
        .then(() => {
          deleteOss(url)
          this.$message.success('删除成功！')
          this.getData(1)
        })
        .catch(err => {
          this.$message.error('删除失败，请重试！')
          throw new Error(err)
        })
    },
    deleteData(id) {
      return this.$api.deleteData(this.$serviceName, this.tableName, id)
    },
  },
}
</script>

<style lang="scss" scoped>
.attach-title {
  font-size: 1.1rem;
  font-weight: bold;
}
</style>
